import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getDepartmentList, createDepartment, updateDepartment, deleteDepartment } from '../../services/api';

const DepartmentList = () => {
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingDepartment, setEditingDepartment] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
    total: 0,
  });

  const fetchDepartments = async () => {
    setLoading(true);
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
        setPagination(prev => ({
          ...prev,
          total: response.data.length
        }));
      } else {
        setDepartments([]);
        setPagination(prev => ({
          ...prev,
          total: 0
        }));
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
      setPagination(prev => ({
        ...prev,
        total: 0
      }));
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchDepartments();
  }, []);

  const handleAdd = () => {
    setEditingDepartment(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingDepartment(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteDepartment(id);
      if (response.code === 200) {
        message.success('删除成功');
        fetchDepartments();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingDepartment) {
        const response = await updateDepartment(editingDepartment.depId, values);
        if (response.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchDepartments();
        } else {
          message.error(response.message || '更新失败');
        }
      } else {
        const response = await createDepartment(values);
        if (response.code === 200) {
          message.success('创建成功');
          setModalVisible(false);
          fetchDepartments();
        } else {
          message.error(response.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  const columns = [
    {
      title: '部门ID',
      dataIndex: 'depId',
      key: 'depId',
    },
    {
      title: '部门名称',
      dataIndex: 'depName',
      key: 'depName',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.depId)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <h2>部门管理</h2>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={handleAdd}
        style={{ marginBottom: 16 }}
      >
        添加部门
      </Button>
      
      <Table
        columns={columns}
        dataSource={departments}
        loading={loading}
        rowKey="depId"
        pagination={pagination}
        onChange={handleTableChange}
      />

      <Modal
        title={editingDepartment ? '编辑部门' : '添加部门'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="depId"
            label="部门ID"
            rules={[{ required: true, message: '请输入部门ID' }]}
          >
            <Input disabled={!!editingDepartment} />
          </Form.Item>
          <Form.Item
            name="depName"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentList; 